package com.cgbl.cg.vm.mine

import android.app.Application
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.CourseServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.CourseBean
import com.robot.base.model.CourseInfoBean
import com.robot.base.model.PageListBean
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse


class CourseCenterViewModel(application: Application) : GLBaseViewModel(application) {

    val tabType = ObservableInt(TAB_COURSE)

    val uc = UiChangeEvent()

    val clickSelectCourse = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_COURSE)
        fetchCourseList()
    })

    val clickSelectCollection = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_COLLECTION)
        fetchCourseList()
    })

    var page = 1

    val pageSize = 10


    class UiChangeEvent {

        val courseInfoData: SingleLiveEvent<List<CourseBean>> = SingleLiveEvent()

        val loadMoreCourseInfoData: SingleLiveEvent<List<CourseBean>> = SingleLiveEvent()

    }

    fun refresh() {
        page = 1
        fetchCourseList()
    }

    fun loadMore() {
        page++
        fetchCourseList()
    }

    fun fetchCourseList() {
        val params = mapOf(
            "type" to tabType.get(), "pageNo" to page, "pageSize" to pageSize
        )
        CourseServiceFactory.getMyCourse(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CourseBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CourseBean>>) {
                if (page == 1) {
                    uc.courseInfoData.postValue(t.data.list)
                } else {
                    uc.loadMoreCourseInfoData.postValue(t.data.list)
                }
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                uc.courseInfoData.postValue(listOf())
            }
        })
    }

    companion object {

        const val TAB_COURSE = 0

        const val TAB_COLLECTION = 1
    }
}